package com.jy.api.util;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@EnableConfigurationProperties(WxMAProperties.class)
public class WxMAConfiguration {
//    private final WxMaMessageHandler templateMsgHandler = new WxMaMessageHandler() {
//        @Override
//        public WxMaXmlOutMessage handle(WxMaMessage wxMaMessage, Map<String, Object> map, WxMaService wxMaService, WxSessionManager wxSessionManager) throws WxErrorException {
//            List<WxMaTemplateData> data = Lists.newArrayList();
//             wxMaService.getMsgService().sendTemplateMsg(WxMaTemplateMessage.builder()
//                    .templateId("此处更换为自己的模板id")
//                    .formId("自己替换可用的formid")
//                    .data(data)
//                    .toUser(wxMaMessage.getFromUser())
//                    .build());
//            return null;
//        }
//    };
//
//    private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> {
//        System.out.println("收到消息：" + wxMessage.toString());
//        service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为：" + wxMessage.toJson())
//                .toUser(wxMessage.getFromUser()).build());
//    };
//
//    private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) ->
//            service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息")
//                    .toUser(wxMessage.getFromUser()).build());
//
//    private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> {
//        try {
//            WxMediaUploadResult uploadResult = service.getMediaService()
//                    .uploadMedia("image", "png",
//                            ClassLoader.getSystemResourceAsStream("tmp.png"));
//            service.getMsgService().sendKefuMsg(
//                    WxMaKefuMessage
//                            .newImageBuilder()
//                            .mediaId(uploadResult.getMediaId())
//                            .toUser(wxMessage.getFromUser())
//                            .build());
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//        }
//    };
//
//    private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> {
//        try {
//            final File file = service.getQrcodeService().createQrcode("123", 430);
//            WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);
//            service.getMsgService().sendKefuMsg(
//                    WxMaKefuMessage
//                            .newImageBuilder()
//                            .mediaId(uploadResult.getMediaId())
//                            .toUser(wxMessage.getFromUser())
//                            .build());
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//        }
//    };

    private static WxMAProperties properties = null;

    private static Map<String, WxMaMessageRouter> routers = Maps.newHashMap();
    private static Map<String, WxMaService> maServices = Maps.newHashMap();

    @Autowired
    public WxMAConfiguration(WxMAProperties properties) {
        WxMAConfiguration.properties = properties;
    }

    public static Map<String, WxMaMessageRouter> getRouters() {
        return routers;
    }

    public static WxMaService getMaService(String appid) {
        WxMaService wxService = maServices.get(appid);
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        return wxService;
    }

    public static WxMaService getMaService(int index) {
        WxMaService wxService = maServices.get(WxMAConfiguration.properties.getConfigs().get(index).getAppid());
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("未找到对应index=[%s]的配置，请核实！", index));
        }

        return wxService;
    }

    @Bean
    public Object services() {
        maServices = WxMAConfiguration.properties.getConfigs()
                .stream()
                .map(a -> {
                    WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
                    config.setAppid(a.getAppid());
                    config.setSecret(a.getSecret());
                    config.setToken(a.getToken());
                    config.setAesKey(a.getAesKey());
                    config.setMsgDataFormat(a.getMsgDataFormat());

                    WxMaService service = new WxMaServiceImpl();
                    service.setWxMaConfig(config);
                    routers.put(a.getAppid(), this.newRouter(service));
                    return service;
                }).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a));

        return Boolean.TRUE;
    }

    private WxMaMessageRouter newRouter(WxMaService service) {
        final WxMaMessageRouter router = new WxMaMessageRouter(service);
//        router
//                .rule().handler(logHandler).next()
//                .rule().async(false).content("模板").handler(templateMsgHandler).end()
//                .rule().async(false).content("文本").handler(textHandler).end()
//                .rule().async(false).content("图片").handler(picHandler).end()
//                .rule().async(false).content("二维码").handler(qrcodeHandler).end();
        return router;
    }
}
